Stored Procedure
Executing stored procedures to perform complex data manipulation tasks in a structured, efficient, and reusable manner.
π§© Overviewβ
A Stored Procedure is a precompiled collection of SQL statements stored within the database. It allows for the execution of complex operations such as insertions, updates, calculations, or validations with optimal performance and control.
π― Use Casesβ
- Encapsulate business logic at the database level
- Execute batch processes (e.g., monthly billing, report generation)
- Implement data integrity rules (e.g., audit logging, trigger-like workflows)
- Reduce application-database round-trips for performance
βοΈ Structure of a Stored Procedureβ
Basic Syntax (SQL Server / MySQL):β
CREATE PROCEDURE procedure_name (
IN input_param INT,
OUT output_param VARCHAR(50)
)
BEGIN
-- SQL Statements
SELECT column_name INTO output_param FROM table WHERE id = input_param;
END;
Example: Insert with Validationβ
CREATE PROCEDURE AddNewPatient (
IN p_name VARCHAR(100),
IN p_mobile VARCHAR(15),
OUT p_result VARCHAR(100)
)
BEGIN
DECLARE existing INT;
SELECT COUNT(*) INTO existing FROM patients WHERE mobile = p_mobile;
IF existing = 0 THEN
INSERT INTO patients (name, mobile) VALUES (p_name, p_mobile);
SET p_result = 'Patient added successfully';
ELSE
SET p_result = 'Duplicate mobile number';
END IF;
END;
π Input/Output Parametersβ
- IN: Accepts values from the caller
- OUT: Returns values to the caller
- INOUT: Accepts and returns values
π Benefitsβ
- π Performance: Reduces SQL compilation time as it's precompiled
- π Reusability: Can be invoked from multiple apps or modules
- π Security: Restrict direct table access by encapsulating logic
- π§± Modularity: Isolates logic for better maintainability
π Execution (via Application)β
From SQL Client:β
CALL AddNewPatient('John Doe', '9876543210', @msg);
SELECT @msg;
From Application Code (Node.js Example):β
const [rows] = await db.execute(
"CALL AddNewPatient(?, ?, @msg); SELECT @msg;",
["John Doe", "9876543210"]
);
console.log(rows[1]); // Result from @msg
π Logging and Error Handlingβ
Add error handling to stored procedures:
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
SET p_result = 'SQL Error occurred';
END;
Optional: Log into a system log table for audit and traceability.
π Best Practicesβ
- Use meaningful names for procedures and parameters
- Avoid business logic complexity thatβs hard to debug
- Keep them short and modular
- Document each procedureβs purpose and input/output clearly
- Use transactions when multiple operations must succeed or fail as one
π¬ Testing Proceduresβ
- Use mock tables and test inputs
- Validate all edge cases (e.g., nulls, duplicates, invalid data types)
- Confirm rollback behavior in transaction scopes
β Success Criteriaβ
Criteria | Condition |
---|---|
Procedure executes cleanly | No runtime errors or SQL exceptions |
Output is accurate | Valid return data / status |
Reusable logic | Works for a range of input parameters |
Secure access | Only allowed users can execute |
π§© Related Conceptsβ
- Triggers: Automatic execution on data change (less flexible)
- Functions: Return a value but cannot modify data
- Views: Represent read-only or computed results
π Summaryβ
Stored Procedures are vital tools in backend systems where performance, logic encapsulation, and security are crucial. They should be used strategically to balance control, reusability, and maintainability.